package com.shaozi.nc.manage.observer;

import java.util.List;
import java.util.Observable;
import java.util.Observer;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;

import com.shaozi.lib.throwable.SzException;
import com.shaozi.nc.data.model.CompanyInfoModel;
import com.shaozi.nc.data.model.MqApiQuartzModel;
import com.shaozi.nc.manage.secretary.SecretaryApiQuartzManage;

/**
 * 系统启动时执行
 * 
 * @author brenx
 *
 */
public class SecretaryApiStartupObserver implements Observer {

	@Autowired
	private SecretaryApiQuartzManage secretaryApiQuartzMgr;
	private Logger logger = Logger.getLogger(SecretaryApiStartupObserver.class);

	public SecretaryApiStartupObserver() {
	}

	@Override
	public void update(Observable o, Object arg) {
		if (arg instanceof CompanyInfoModel) {
			CompanyInfoModel model = (CompanyInfoModel) arg;
			updateCompany(model);
		}

	}

	/**
	 * 恢复各个公司保存的调度程序
	 * 
	 * @param company
	 */
	private void updateCompany(CompanyInfoModel company) {
		if (company == null) {
			return;
		}
		try {
			List<MqApiQuartzModel> models = secretaryApiQuartzMgr.listAll(company.getCompanyId());
			for (MqApiQuartzModel model : models) {
				boolean ok = secretaryApiQuartzMgr.schedule(company.getCompany_id(), model);
				if (!ok) {
					secretaryApiQuartzMgr.removeSchedule(company.getCompany_id(), model);
				}
			}
		} catch (SzException e) {
			logger.error(e.getStackMessage());
		}
	}

}
